import gradio as gr
import pandas as pd
import numpy as np
import random
import time
import psutil
from datetime import datetime



def main():
    df = pd.DataFrame({
        'height': np.random.randint(50, 70, 25),
        'weight': np.random.randint(120, 320, 25),
        'age': np.random.randint(18, 65, 25),
        'ethnicity': [random.choice(["white", "black", "asian"]) for _ in range(25)]
    })

    with gr.Blocks() as demo:
        gr.LinePlot(df, x="weight", y="height")

    demo.launch()



# 初始化一个空的 DataFrame 用于存储 CPU 使用率
df = pd.DataFrame(columns=["Timestamp", "CPU Usage %", "MEM Usage %"])

def record_cpu_usage():
    global df
    # 获取当前时间的时间戳
    timestamp = time.time()
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")

    # 获取当前 CPU 使用率
    cpu_usage = psutil.cpu_percent(interval=None)

    # 获取当前 内存 使用率
    memory = psutil.virtual_memory()
    
    # 创建新的一行数据
    new_row = pd.DataFrame([[now, cpu_usage, memory.percent]], columns=["Timestamp", "CPU Usage %", "MEM Usage %"])
    
    # 使用 concat 合并新的数据行到 DataFrame
    df = pd.concat([df, new_row], ignore_index=True)
    
    # 如果记录数超过 100，移除最早的记录
    while len(df) > 30:
        df.drop(df.index[0], inplace=True)
    
    return df


def get_df():
    def inner():
        return record_cpu_usage()
    return inner



def get_df2():
    def inner():
        global df
        return df
    return inner


def main2():
    with gr.Blocks() as demo:
        gr.LinePlot(value=get_df(), x="Timestamp", y="CPU Usage %", every=3, x_label_angle=45)

    demo.launch()




def main3():
    from datetime import datetime, timedelta
    now = datetime.now()

    df = pd.DataFrame({
        'time': [now - timedelta(minutes=5*i) for i in range(25)],
        'price': np.random.randint(100, 1000, 25),
        'origin': [random.choice(["DFW", "DAL", "HOU"]) for _ in range(25)],
        'destination': [random.choice(["JFK", "LGA", "EWR"]) for _ in range(25)],
    })

    with gr.Blocks() as demo:
        gr.LinePlot(df, x="time", y="price")
        gr.ScatterPlot(df, x="time", y="price", color="origin")

    demo.launch()



def main4():

    with gr.Blocks() as demo:
        gr.LinePlot(value=get_df(), x="Timestamp", y="CPU Usage %", every=3, x_label_angle=0)
        # 第二个不用调用更新, 直接取结果
        gr.LinePlot(value=get_df2(), x="Timestamp", y="MEM Usage %", every=3, x_label_angle=0)
    
    demo.launch()


def main5():
    from data import df

    with gr.Blocks() as demo:
        plot = gr.BarPlot(df, x="time", y="price", x_bin="10m")

        bins = gr.Radio(["10m", "30m", "1h"], label="Bin Size")
        bins.change(lambda bins: gr.BarPlot(x_bin=bins), bins, plot)

    demo.launch()



# 实时数据, 使用 gr.Timer(5) 对象 或者 every 属性

def get_data():
    from datetime import datetime, timedelta
    now = datetime.now()

    df = pd.DataFrame({
        'time': [now - timedelta(minutes=5*i) for i in range(25)],
        'price': np.random.randint(100, 1000, 25),
        'origin': [random.choice(["DFW", "DAL", "HOU"]) for _ in range(25)],
        'destination': [random.choice(["JFK", "LGA", "EWR"]) for _ in range(25)],
    })
    return df

def main6():
    with gr.Blocks() as demo:
        timer = gr.Timer(5)
        plot1 = gr.BarPlot(x="time", y="price")
        plot2 = gr.BarPlot(x="time", y="price", color="origin")

        timer.tick(lambda: [get_data(), get_data()], outputs=[plot1, plot2])
    demo.launch()

if __name__ == '__main__':
    main6()